package middleware

import (
	"addsvc/internal/utils/method"
	"time"

	"github.com/go-kit/kit/circuitbreaker"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/ratelimit"
	"github.com/go-kit/log"
	"github.com/sony/gobreaker"
	"golang.org/x/time/rate"
)

func Chains(method method.Method, logger log.Logger) endpoint.Middleware {

	return func(endpoint endpoint.Endpoint) endpoint.Endpoint {
		// 限流
		endpoint = ratelimit.NewErroringLimiter(rate.NewLimiter(rate.Every(500*time.Millisecond), 100))(endpoint)

		// 断路器
		endpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{
			Name:    string(method),
			Timeout: 30 * time.Second,
		}))(endpoint)

		// 日志
		endpoint = Logging(log.With(logger, "method", method))(endpoint)
		return endpoint
	}
}
